import Fly from 'flyio/dist/npm/wx'
import { api, api_model } from '@/ui-domain'
const fly = new Fly()
import * as Foundation from '@/utils/Foundation.js'
import md5 from 'js-md5'
//var util = require('./uuid.js');
//let accessToken = 'eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjIwNiwic3ViIjoiQlVZRVIiLCJyb2xlcyI6WyJCVVlFUiJdLCJvcGVyYXRlUm9sZUlkIjo5LCJleHAiOjE1OTM3NDE4NzksInV1aWQiOm51bGwsInVzZXJuYW1lIjoibGoxNTUxOTE4MzE2NSIsIm9wZXJhdGVSb2xlTmFtZSI6Iuawv-WPiyJ9.wsSbIcpyjpdMxLbp_4_Z7RxfZYyjyT0JoOTtvD4o3gbJACDpUwfK9LQSNumh4EjJ1zzS_sgOzCaCVavvk7pGqA'
//const config = api_model
//添加请求拦截器
fly.interceptors.request.use((request) => {
	const uuid = uni.getStorageSync('UUID')
	const accessToken = uni.getStorageSync('token')
	const {needToken,params} = request
	
	if(needToken){
		wx.showLoading({
		  title: "加载中",
		  mask:true
		});
	}
  request.headers = {
  	"X-Tag": "flyio",
  	'content-type': 'application/json',
  	'uuid':uuid,
    'Authorization': accessToken
  }; 
  // if(request.body!={} && request.body){
	request.body && Object.keys(request.body).forEach((val) => {
	  if(request.body[val] === ""){
	    delete request.body[val]
	  }
	})  
  // }
  if(request.needToken && accessToken){
	if(api_model=== 'dev'){
		request.body = {
		  ...request.body
		} 
		
	}else{
		const uid = uni.getStorageSync('userInfo').uid
		const nonce = Foundation.randomString(6)
		const timestamp = parseInt(new Date().getTime() / 1000)
		const sign = md5(uid+nonce+timestamp+accessToken)
		 const _params = { uid,nonce,timestamp, sign }
		request.body = {
			...request.body,
		}
		request.params = {
			...params,
			..._params
		}
	}
	fly.unlock();//解锁请求
	return request;
  }
}, (error, promise) => {
	promise.reject(error)
});

//添加响应拦截器
fly.interceptors.response.use(
  async (response) => {
    await closeLoading(response)
    return response.data;//请求成功之后将返回值返回
  },
  async (err, promise) => {
	  // console.log("err is=====>", err)
	  let uuid_old = uni.getStorageSync('UUID') || ''
	  let uuid_oold = uuid_old
	  // let shop_id_old = uni.getStorageSync('shop_id')
	  let izShow = true
      await closeLoading(err)
      let msg = '';
      if (err.status === 0) {
        msg = '网络连接异常'
      } else if (err.status === 1) {
        msg = '网络连接超时'
      } else if (err.status === 401) {
        msg = '用户未登录'
      } else if (err.status === 403) {
        // msg = '登录已失效'
		// wx.clearStorageSync()
		izShow = false
		uni.clearStorageSync()
		// uni.setStorageSync('shop_id',shop_id_old)
		wx.navigateTo({
		  url: '../login/login'
		});
      }else {
        if (err.response.data.message) {
			if(err.response.data.code ==='150'){
				izShow = false
			}else{
				msg = err.response.data.message
			}
        } else {
          msg = '请求数据失败,请稍后再试'
        }
      }
	  if(izShow){
		wx.showToast({
		    title: msg,
		    icon: 'none',
		    duration: 2000
		})
	  }else{
		  wx.hideToast()
	  }
      return promise.resolve(err)
    }
);
//设置超时
fly.config.timeout = 30000;
fly.config.baseURL = api.chat;

const closeLoading = (target) => {
	// console.log('target',target)
  // if (!target.config || !target.config.loading) return true
  return new Promise((resolve, reject) => {
    setTimeout(() => {
		wx.hideLoading();
		resolve()
    }, 200)
  })
}
export default fly;
